<!DOCTYPE html><!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]--><!--[if gt IE 8]><!--><html class="no-js" lang="en"><!--<![endif]--><head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  
  <link rel="canonical" href="https://sequelize.org/v3/docs/docs/models-usage/">
  <link rel="shortcut icon" href="/v3/favicon.ico">
  
  <title>Usage - Sequelize | The Node.js / io.js ORM for PostgreSQL, MySQL, SQLite and MSSQL</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700|Roboto+Slab:400,700|Inconsolata:400,700">

  <link rel="stylesheet" href="/v3/css/theme.css">
  <link rel="stylesheet" href="/v3/css/theme_extra.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/github.min.css">
  <link href="/v3/css/custom.css" rel="stylesheet">
  
  <script>
    // Current page data
    var mkdocs_page_name = "Usage";
    var mkdocs_page_input_path = "docs/models-usage.md";
    var mkdocs_page_url = "/v3/docs/models-usage/";
  </script>
  
  <script src="/v3/js/jquery-2.1.1.min.js" defer=""></script>
  <script src="/v3/js/modernizr-2.8.3.min.js" defer=""></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/highlight.min.js"></script>
  <script>hljs.initHighlightingOnLoad();</script> 
<meta name="robots" content="noindex"></head>

<body class="wy-body-for-nav" role="document">

  <div class="wy-grid-for-nav">

    
    <nav data-toggle="wy-nav-shift" class="wy-nav-side stickynav">
    <div class="wy-side-scroll">
      <div class="wy-side-nav-search">
        <a href="/v3" class="icon icon-home"> Sequelize | The Node.js / io.js ORM for PostgreSQL, MySQL, SQLite and MSSQL</a>
        <div role="search">
  <form id="rtd-search-form" class="wy-form" action="/v3/search.html" method="get">
      <input type="text" name="q" placeholder="Search docs" title="Type search term here">
  </form>
</div>
      </div>

      <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="/v3">Home</a>
                    </li>
                </ul>
                <p class="caption"><span class="caption-text">Documentation</span></p>
                <ul class="current">
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/getting-started/">Getting Started</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/schema/">Working with table schemas</a>
                    </li>
                    <li class="toctree-l1 current"><a class="reference internal current" href="#">Models</a>
    <ul class="current">
                <li class="toctree-l2"><a class="reference internal" href="/v3/docs/models-definition/">Definition</a>
                </li>
                <li class="toctree-l2 current"><a class="reference internal current" href="./">Usage</a>
    <ul class="current">
    <li class="toctree-l3"><a class="reference internal" href="#find-search-for-one-specific-element-in-the-database">find - Search for one specific element in the database</a>
    </li>
    <li class="toctree-l3"><a class="reference internal" href="#findorcreate-search-for-a-specific-element-or-create-it-if-not-available">findOrCreate - Search for a specific element or create it if not available</a>
    </li>
    <li class="toctree-l3"><a class="reference internal" href="#findandcountall-search-for-multiple-elements-in-the-database-returns-both-data-and-total-count">findAndCountAll - Search for multiple elements in the database, returns both data and total count</a>
    </li>
    <li class="toctree-l3"><a class="reference internal" href="#findall-search-for-multiple-elements-in-the-database">findAll - Search for multiple elements in the database</a>
    </li>
    <li class="toctree-l3"><a class="reference internal" href="#complex-filtering-or-not-queries">Complex filtering / OR / NOT queries</a>
    </li>
    <li class="toctree-l3"><a class="reference internal" href="#manipulating-the-dataset-with-limit-offset-order-and-group">Manipulating the dataset with limit, offset, order and group</a>
    </li>
    <li class="toctree-l3"><a class="reference internal" href="#raw-queries">Raw queries</a>
    </li>
    <li class="toctree-l3"><a class="reference internal" href="#count-count-the-occurrences-of-elements-in-the-database">count - Count the occurrences of elements in the database</a>
    </li>
    <li class="toctree-l3"><a class="reference internal" href="#max-get-the-greatest-value-of-a-specific-attribute-within-a-specific-table">max - Get the greatest value of a specific attribute within a specific table</a>
    </li>
    <li class="toctree-l3"><a class="reference internal" href="#min-get-the-least-value-of-a-specific-attribute-within-a-specific-table">min - Get the least value of a specific attribute within a specific table</a>
    </li>
    <li class="toctree-l3"><a class="reference internal" href="#sum-sum-the-value-of-specific-attributes">sum - Sum the value of specific attributes</a>
    </li>
    </ul>
                </li>
    </ul>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/querying/">Querying</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/scopes/">Scopes</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/instances/">Instances</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/associations/">Relations / Associations</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/hooks/">Hooks</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/transactions/">Transactions</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/legacy/">Working with legacy tables</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/raw-queries/">Raw queries</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/docs/migrations/">Migrations</a>
                    </li>
                </ul>
                <p class="caption"><span class="caption-text">API</span></p>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/sequelize/">Sequelize</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/model/">Model</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/instance/">Instance</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="#">Associations</a>
    <ul>
                <li class="toctree-l2"><a class="reference internal" href="/v3/api/associations/">Overview</a>
                </li>
                <li class="toctree-l2"><a class="reference internal" href="/v3/api/associations/belongs-to/">BelongsTo (1:1)</a>
                </li>
                <li class="toctree-l2"><a class="reference internal" href="/v3/api/associations/has-one/">HasOne (1:1)</a>
                </li>
                <li class="toctree-l2"><a class="reference internal" href="/v3/api/associations/has-many/">HasMany (1:m)</a>
                </li>
                <li class="toctree-l2"><a class="reference internal" href="/v3/api/associations/belongs-to-many/">BelongsToMany (n:m)</a>
                </li>
    </ul>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/hooks/">Hooks</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/transaction/">Transaction</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/datatypes/">Datatypes</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/deferrable/">Deferrable</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/api/errors/">Errors</a>
                    </li>
                </ul>
                <p class="caption"><span class="caption-text">Misc</span></p>
                <ul>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/changelog/">Changelog</a>
                    </li>
                    <li class="toctree-l1"><a class="reference internal" href="/v3/imprint/">Imprint</a>
                    </li>
                </ul>
      </div>
    </div>
    </nav>

    <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">

      
      <nav class="wy-nav-top" role="navigation" aria-label="top navigation">
        <i data-toggle="wy-nav-top" class="fa fa-bars"></i>
        <a href="/v3">Sequelize | The Node.js / io.js ORM for PostgreSQL, MySQL, SQLite and MSSQL</a>
      </nav>

      
      <div class="wy-nav-content">
        <div class="rst-content">
          <div role="navigation" aria-label="breadcrumbs navigation">
  <ul class="wy-breadcrumbs">
    <li><a href="/v3">Docs</a> »</li>
    
      
        
          <li>Documentation »</li>
        
      
        
          <li>Models »</li>
        
      
    
    <li>Usage</li>
    <li class="wy-breadcrumbs-aside">
      
        <a href="https://github.com/sequelize/sequelize/edit/master/docs/docs/models-usage.md" class="icon icon-github"> Edit on GitHub</a>
      
    </li>
  </ul>
  
  <hr>
</div>

          <div role="main">
            <div class="section">
              
                <h2 id="data-retrieval-finders">Data retrieval / Finders</h2>
<p>Finder methods are intended to query data from the database. They do <em>not</em> return plain objects but instead return model instances. Because finder methods return model instances you can call any model instance member on the result as described in the documentation for <a href="https://sequelize.org/v3/docs/en/latest/docs/instances/"><em>instances</em></a>.</p>
<p>In this document we'll explore what finder methods can do:</p>
<h3 id="find-search-for-one-specific-element-in-the-database">find - Search for one specific element in the database</h3>
<pre><code class="language-js">// search for known ids
Project.findById(123).then(function(project) {
  // project will be an instance of Project and stores the content of the table entry
  // with id 123. if such an entry is not defined you will get null
})

// search for attributes
Project.findOne({ where: {title: 'aProject'} }).then(function(project) {
  // project will be the first entry of the Projects table with the title 'aProject' || null
})


Project.findOne({
  where: {title: 'aProject'},
  attributes: ['id', ['name', 'title']]
}).then(function(project) {
  // project will be the first entry of the Projects table with the title 'aProject' || null
  // project.title will contain the name of the project
})
</code></pre>
<h3 id="findorcreate-search-for-a-specific-element-or-create-it-if-not-available">findOrCreate - Search for a specific element or create it if not available</h3>
<p>The method <code>findOrCreate</code> can be used to check if a certain element already exists in the database. If that is the case the method will result in a respective instance. If the element does not yet exist, it will be created.</p>
<p>Let's assume we have an empty database with a <code>User</code> model which has a <code>username</code> and a <code>job</code>.</p>
<pre><code class="language-js">User
  .findOrCreate({where: {username: 'sdepold'}, defaults: {job: 'Technical Lead JavaScript'}})
  .spread(function(user, created) {
    console.log(user.get({
      plain: true
    }))
    console.log(created)

    /*
      {
        username: 'sdepold',
        job: 'Technical Lead JavaScript',
        id: 1,
        createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET),
        updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET)
      }
      created: true
    */
  })
</code></pre>
<p>The code created a new instance. So when we already have an instance ...</p>
<pre><code class="language-js">User
  .create({ username: 'fnord', job: 'omnomnom' })
  .then(function() {
    User
      .findOrCreate({where: {username: 'fnord'}, defaults: {job: 'something else'}})
      .spread(function(user, created) {
        console.log(user.get({
          plain: true
        }))
        console.log(created)

        /*
          {
            username: 'fnord',
            job: 'omnomnom',
            id: 2,
            createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET),
            updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET)
          }
          created: false
        */
      })
  })
</code></pre>
<p>... the existing entry will not be changed. See the <code>job</code> of the second user, and the fact that created was false.</p>
<h3 id="findandcountall-search-for-multiple-elements-in-the-database-returns-both-data-and-total-count">findAndCountAll - Search for multiple elements in the database, returns both data and total count</h3>
<p>This is a convenience method that combines<code>findAll</code> and <code>count</code> (see below) this is useful when dealing with queries related to pagination where you want to retrieve data with a <code>limit</code> and <code>offset</code> but also need to know the total number of records that match the query:</p>
<p>The success handler will always receive an object with two properties:</p>
<ul>
<li><code>count</code> - an integer, total number records matching the where clause</li>
<li><code>rows</code> - an array of objects, the records matching the where clause, within the limit and offset range</li>
</ul>
<pre><code class="language-js">Project
  .findAndCountAll({
     where: {
        title: {
          $like: 'foo%'
        }
     },
     offset: 10,
     limit: 2
  })
  .then(function(result) {
    console.log(result.count);
    console.log(result.rows);
  });
</code></pre>
<p><code>findAndCountAll</code> also supports includes. Only the includes that are marked as <code>required</code> will be added to the count part:</p>
<p>Suppose you want to find all users who have a profile attached:</p>
<pre><code class="language-js">User.findAndCountAll({
  include: [
     { model: Profile, required: true}
  ],
  limit: 3
});
</code></pre>
<p>Because the include for <code>Profile</code> has <code>required</code> set it will result in an inner join, and only the users who have a profile will be counted. If we remove <code>required</code> from the include, both users with and without profiles will be counted. Adding a <code>where</code> clause to the include automatically makes it required:</p>
<pre><code class="language-js">User.findAndCountAll({
  include: [
     { model: Profile, where: { active: true }}
  ],
  limit: 3
});
</code></pre>
<p>The query above will only count users who have an active profile, because <code>required</code> is implicitly set to true when you add a where clause to the include.</p>
<p>The options object that you pass to <code>findAndCountAll</code> is the same as for <code>findAll</code> (described below).</p>
<h3 id="findall-search-for-multiple-elements-in-the-database">findAll - Search for multiple elements in the database</h3>
<pre><code class="language-js">// find multiple entries
Project.findAll().then(function(projects) {
  // projects will be an array of all Project instances
})

// also possible:
Project.all().then(function(projects) {
  // projects will be an array of all Project instances
})

// search for specific attributes - hash usage
Project.findAll({ where: { name: 'A Project' } }).then(function(projects) {
  // projects will be an array of Project instances with the specified name
})

// search with string replacements
Project.findAll({ where: ["id &gt; ?", 25] }).then(function(projects) {
  // projects will be an array of Projects having a greater id than 25
})

// search within a specific range
Project.findAll({ where: { id: [1,2,3] } }).then(function(projects) {
  // projects will be an array of Projects having the id 1, 2 or 3
  // this is actually doing an IN query
})

Project.findAll({
  where: {
    id: {
      $and: {a: 5}           // AND (a = 5)
      $or: [{a: 5}, {a: 6}]  // (a = 5 OR a = 6)
      $gt: 6,                // id &gt; 6
      $gte: 6,               // id &gt;= 6
      $lt: 10,               // id &lt; 10
      $lte: 10,              // id &lt;= 10
      $ne: 20,               // id != 20
      $between: [6, 10],     // BETWEEN 6 AND 10
      $notBetween: [11, 15], // NOT BETWEEN 11 AND 15
      $in: [1, 2],           // IN [1, 2]
      $notIn: [1, 2],        // NOT IN [1, 2]
      $like: '%hat',         // LIKE '%hat'
      $notLike: '%hat'       // NOT LIKE '%hat'
      $iLike: '%hat'         // ILIKE '%hat' (case insensitive)  (PG only)
      $notILike: '%hat'      // NOT ILIKE '%hat'  (PG only)
      $overlap: [1, 2]       // &amp;&amp; [1, 2] (PG array overlap operator)
      $contains: [1, 2]      // @&gt; [1, 2] (PG array contains operator)
      $contained: [1, 2]     // &lt;@ [1, 2] (PG array contained by operator)
      $any: [2,3]            // ANY ARRAY[2, 3]::INTEGER (PG only)
    },
    status: {
      $not: false,           // status NOT FALSE
    }
  }
})
</code></pre>
<h3 id="complex-filtering-or-not-queries">Complex filtering / OR / NOT queries</h3>
<p>It's possible to do complex where queries with multiple levels of nested AND, OR and NOT conditions. In order to do that you can use <code>$or</code>, <code>$and</code> or <code>$not</code>:</p>
<pre><code class="language-js">Project.findOne({
  where: {
    name: 'a project',
    $or: [
      { id: [1,2,3] },
      { id: { $gt: 10 } }
    ]
  }
})

Project.findOne({
  where: {
    name: 'a project',
    id: {
      $or: [
        [1,2,3],
        { $gt: 10 }
      ]
    }
  }
})
</code></pre>
<p>Both pieces of code code will generate the following:</p>
<pre><code class="language-sql">SELECT *
FROM `Projects`
WHERE (
  `Projects`.`name` = 'a project'
   AND (`Projects`.`id` IN (1,2,3) OR `Projects`.`id` &gt; 10)
)
LIMIT 1;
</code></pre>
<p><code>$not</code> example:</p>
<pre><code class="language-js">Project.findOne({
  where: {
    name: 'a project',
    $not: [
      { id: [1,2,3] },
      { array: { $contains: [3,4,5] } }
    ]
  }
});
</code></pre>
<p>Will generate:</p>
<pre><code class="language-sql">SELECT *
FROM `Projects`
WHERE (
  `Projects`.`name` = 'a project'
   AND NOT (`Projects`.`id` IN (1,2,3) OR `Projects`.`array` @&gt; ARRAY[1,2,3]::INTEGER[])
)
LIMIT 1;
</code></pre>
<h3 id="manipulating-the-dataset-with-limit-offset-order-and-group">Manipulating the dataset with limit, offset, order and group</h3>
<p>To get more relevant data, you can use limit, offset, order and grouping:</p>
<pre><code class="language-js">// limit the results of the query
Project.findAll({ limit: 10 })

// step over the first 10 elements
Project.findAll({ offset: 10 })

// step over the first 10 elements, and take 2
Project.findAll({ offset: 10, limit: 2 })
</code></pre>
<p>The syntax for grouping and ordering are equal, so below it is only explained with a single example for group, and the rest for order. Everything you see below can also be done for group</p>
<pre><code class="language-js">Project.findAll({order: 'title DESC'})
// yields ORDER BY title DESC

Project.findAll({group: 'name'})
// yields GROUP BY name
</code></pre>
<p>Notice how in the two examples above, the string provided is inserted verbatim into the query, i.e. column names are not escaped. When you provide a string to order/group, this will always be the case. If you want to escape column names, you should provide an array of arguments, even though you only want to order/group by a single column</p>
<pre><code class="language-js">something.findOne({
  order: [
    'name',
    // will return `name`
    'username DESC',
    // will return `username DESC` -- i.e. don't do it!
    ['username', 'DESC'],
    // will return `username` DESC
    sequelize.fn('max', sequelize.col('age')),
    // will return max(`age`)
    [sequelize.fn('max', sequelize.col('age')), 'DESC'],
    // will return max(`age`) DESC
    [sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'],
    // will return otherfunction(`col1`, 12, 'lalala') DESC
    [sequelize.fn('otherfunction', sequelize.fn('awesomefunction', sequelize.col('col'))), 'DESC']
    // will return otherfunction(awesomefunction(`col`)) DESC, This nesting is potentially infinite!
    [{ raw: 'otherfunction(awesomefunction(`col`))' }, 'DESC']
    // This won't be quoted, but direction will be added
  ]
})
</code></pre>
<p>To recap, the elements of the order/group array can be the following:</p>
<ul>
<li>String - will be quoted</li>
<li>Array - first element will be quoted, second will be appended verbatim</li>
<li>Object -</li>
<li>Raw will be added verbatim without quoting</li>
<li>Everything else is ignored, and if raw is not set, the query will fail</li>
<li>Sequelize.fn and Sequelize.col returns functions and quoted cools</li>
</ul>
<h3 id="raw-queries">Raw queries</h3>
<p>Sometimes you might be expecting a massive dataset that you just want to display, without manipulation. For each row you select, Sequelize creates an instance with functions for update, delete, get associations etc. If you have thousands of rows, this might take some time. If you only need the raw data and don't want to update anything, you can do like this to get the raw data.</p>
<pre><code class="language-js">// Are you expecting a massive dataset from the DB,
// and don't want to spend the time building DAOs for each entry?
// You can pass an extra query option to get the raw data instead:
Project.findAll({ where: { ... }, raw: true })
</code></pre>
<h3 id="count-count-the-occurrences-of-elements-in-the-database">count - Count the occurrences of elements in the database</h3>
<p>There is also a method for counting database objects:</p>
<pre><code class="language-js">Project.count().then(function(c) {
  console.log("There are " + c + " projects!")
})

Project.count({ where: ["id &gt; ?", 25] }).then(function(c) {
  console.log("There are " + c + " projects with an id greater than 25.")
})
</code></pre>
<h3 id="max-get-the-greatest-value-of-a-specific-attribute-within-a-specific-table">max - Get the greatest value of a specific attribute within a specific table</h3>
<p>And here is a method for getting the max value of an attribute:f</p>
<pre><code class="language-js">/*
  Let's assume 3 person objects with an attribute age.
  The first one is 10 years old,
  the second one is 5 years old,
  the third one is 40 years old.
*/
Project.max('age').then(function(max) {
  // this will return 40
})

Project.max('age', { where: { age: { lt: 20 } } }).then(function(max) {
  // will be 10
})
</code></pre>
<h3 id="min-get-the-least-value-of-a-specific-attribute-within-a-specific-table">min - Get the least value of a specific attribute within a specific table</h3>
<p>And here is a method for getting the min value of an attribute:</p>
<pre><code class="language-js">/*
  Let's assume 3 person objects with an attribute age.
  The first one is 10 years old,
  the second one is 5 years old,
  the third one is 40 years old.
*/
Project.min('age').then(function(min) {
  // this will return 5
})

Project.min('age', { where: { age: { $gt: 5 } } }).then(function(min) {
  // will be 10
})
</code></pre>
<h3 id="sum-sum-the-value-of-specific-attributes">sum - Sum the value of specific attributes</h3>
<p>In order to calculate the sum over a specific column of a table, you can
use the <code>sum</code> method.</p>
<pre><code class="language-js">/*
  Let's assume 3 person objects with an attribute age.
  The first one is 10 years old,
  the second one is 5 years old,
  the third one is 40 years old.
*/
Project.sum('age').then(function(sum) {
  // this will return 55
})

Project.sum('age', { where: { age: { $gt: 5 } } }).then(function(sum) {
  // will be 50
})
</code></pre>
<h2 id="eager-loading">Eager loading</h2>
<p>When you are retrieving data from the database there is a fair chance that you also want to get associations with the same query - this is called eager loading. The basic idea behind that, is the use of the attribute <code>include</code> when you are calling <code>find</code> or <code>findAll</code>. Lets assume the following setup:</p>
<pre><code class="language-js">var User = sequelize.define('user', { name: Sequelize.STRING })
  , Task = sequelize.define('task', { name: Sequelize.STRING })
  , Tool = sequelize.define('tool', { name: Sequelize.STRING })

Task.belongsTo(User)
User.hasMany(Task)
User.hasMany(Tool, { as: 'Instruments' })

sequelize.sync().then(function() {
  // this is where we continue ...
})
</code></pre>
<p>OK. So, first of all, let's load all tasks with their associated user.</p>
<pre><code class="language-js">Task.findAll({ include: [ User ] }).then(function(tasks) {
  console.log(JSON.stringify(tasks))

  /*
    [{
      "name": "A Task",
      "id": 1,
      "createdAt": "2013-03-20T20:31:40.000Z",
      "updatedAt": "2013-03-20T20:31:40.000Z",
      "userId": 1,
      "user": {
        "name": "John Doe",
        "id": 1,
        "createdAt": "2013-03-20T20:31:45.000Z",
        "updatedAt": "2013-03-20T20:31:45.000Z"
      }
    }]
  */
})
</code></pre>
<p>Notice that the accessor (the <code>User</code> property in the resulting instance) is singular because the association is one-to-something.</p>
<p>Next thing: Loading of data with many-to-something associations!</p>
<pre><code class="language-js">User.findAll({ include: [ Task ] }).then(function(users) {
  console.log(JSON.stringify(users))

  /*
    [{
      "name": "John Doe",
      "id": 1,
      "createdAt": "2013-03-20T20:31:45.000Z",
      "updatedAt": "2013-03-20T20:31:45.000Z",
      "tasks": [{
        "name": "A Task",
        "id": 1,
        "createdAt": "2013-03-20T20:31:40.000Z",
        "updatedAt": "2013-03-20T20:31:40.000Z",
        "userId": 1
      }]
    }]
  */
})
</code></pre>
<p>Notice that the accessor (the <code>Tasks</code> property in the resulting instance) is plural because the association is many-to-something.</p>
<p>If an association is aliased (using the <code>as</code> option), you must specify this alias when including the model. Notice how the user's <code>Tool</code>s are aliased as <code>Instruments</code> above. In order to get that right you have to specify the model you want to load, as well as the alias:</p>
<pre><code class="language-js">User.findAll({ include: [{ model: Tool, as: 'Instruments' }] }).then(function(users) {
  console.log(JSON.stringify(users))

  /*
    [{
      "name": "John Doe",
      "id": 1,
      "createdAt": "2013-03-20T20:31:45.000Z",
      "updatedAt": "2013-03-20T20:31:45.000Z",
      "Instruments": [{
        "name": "Toothpick",
        "id": 1,
        "createdAt": null,
        "updatedAt": null,
        "userId": 1
      }]
    }]
  */
})
</code></pre>
<p>When eager loading we can also filter the associated model using <code>where</code>. This will return all <code>User</code>s in which the <code>where</code> clause of <code>Tool</code> model matches rows.</p>
<pre><code class="language-js">User.findAll({
    include: [{
        model: Tool,
        as: 'Instruments',
        where: { name: { $like: '%ooth%' } }
    }]
}).then(function(users) {
    console.log(JSON.stringify(users))

    /*
      [{
        "name": "John Doe",
        "id": 1,
        "createdAt": "2013-03-20T20:31:45.000Z",
        "updatedAt": "2013-03-20T20:31:45.000Z",
        "Instruments": [{
          "name": "Toothpick",
          "id": 1,
          "createdAt": null,
          "updatedAt": null,
          "userId": 1
        }]
      }],

      [{
        "name": "John Smith",
        "id": 2,
        "createdAt": "2013-03-20T20:31:45.000Z",
        "updatedAt": "2013-03-20T20:31:45.000Z",
        "Instruments": [{
          "name": "Toothpick",
          "id": 1,
          "createdAt": null,
          "updatedAt": null,
          "userId": 1
        }]
      }],
    */
  })
</code></pre>
<p>When an eager loaded model is filtered using <code>include.where</code> then <code>include.required</code> is implicitly set to
<code>true</code>. This means that an inner join is done returning parent models with any matching children.</p>
<h3 id="including-everything">Including everything</h3>
<p>To include all attributes, you can pass a single object with <code>all: true</code>:</p>
<pre><code class="language-js">User.findAll({ include: [{ all: true }]});
</code></pre>
<h3 id="including-soft-deleted-records">Including soft deleted records</h3>
<p>In case you want to eager load soft deleted records you can do that by setting <code>include.paranoid</code> to <code>true</code></p>
<pre><code class="language-js">User.findAll({
    include: [{
        model: Tool,
        where: { name: { $like: '%ooth%' } },
        paranoid: true // query and loads the soft deleted records
    }]
});
</code></pre>
<h3 id="ordering-eager-loaded-associations">Ordering Eager Loaded Associations</h3>
<p>In the case of a one-to-many relationship.</p>
<pre><code class="language-js">Company.findAll({ include: [ Division ], order: [ [ Division, 'name' ] ] });
Company.findAll({ include: [ Division ], order: [ [ Division, 'name', 'DESC' ] ] });
Company.findAll({
  include: [ { model: Division, as: 'Div' } ],
  order: [ [ { model: Division, as: 'Div' }, 'name' ] ]
});
Company.findAll({
  include: [ { model: Division, as: 'Div' } ],
  order: [ [ { model: Division, as: 'Div' }, 'name', 'DESC' ] ]
});
Company.findAll({
  include: [ { model: Division, include: [ Department ] } ],
  order: [ [ Division, Department, 'name' ] ]
});
</code></pre>
<p>In the case of many-to-many joins, you are also able to sort by attributes in the through table.</p>
<pre><code class="language-js">Company.findAll({
  include: [ { model: Division, include: [ Department ] } ],
  order: [ [ Division, DepartmentDivision, 'name' ] ]
});
</code></pre>
<h3 id="nested-eager-loading">Nested eager loading</h3>
<p>You can use nested eager loading to load all related models of a related model:</p>
<pre><code class="language-js">User.findAll({
  include: [
    {model: Tool, as: 'Instruments', include: [
      {model: Teacher, include: [ /* etc */]}
    ]}
  ]
}).then(function(users) {
  console.log(JSON.stringify(users))

  /*
    [{
      "name": "John Doe",
      "id": 1,
      "createdAt": "2013-03-20T20:31:45.000Z",
      "updatedAt": "2013-03-20T20:31:45.000Z",
      "Instruments": [{ // 1:M and N:M association
        "name": "Toothpick",
        "id": 1,
        "createdAt": null,
        "updatedAt": null,
        "userId": 1,
        "Teacher": { // 1:1 association
          "name": "Jimi Hendrix"
        }
      }]
    }]
  */
})
</code></pre>
<p>This will produce an outer join. However, a <code>where</code> clause on a related model will create an inner join and return only the instances that have matching sub-models. To return all parent instances, you should add <code>required: false</code>.</p>
<pre><code class="language-js">User.findAll({
  include: [{
    model: Tool,
    as: 'Instruments',
    include: [{
      model: Teacher,
      where: {
        school: "Woodstock Music School"
      },
      required: false
    }]
  }]
}).then(function(users) {
  /* ... */
})
</code></pre>
<p>The query above will return all users, and all their instruments, but only those teachers associated with <code>Woodstock Music School</code>.</p>
<p>Include all also supports nested loading:</p>
<pre><code class="language-js">User.findAll({ include: [{ all: true, nested: true }]});
</code></pre>
              
            </div>
          </div>
          <footer>
  
    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
        <a href="/v3/docs/querying/" class="btn btn-neutral float-right" title="Querying">Next <span class="icon icon-circle-arrow-right"></span></a>
      
      
        <a href="/v3/docs/models-definition/" class="btn btn-neutral" title="Definition"><span class="icon icon-circle-arrow-left"></span> Previous</a>
      
    </div>
  

  <hr>

  <div role="contentinfo">
    <!-- Copyright etc -->
    
  </div>

  Built with <a href="https://www.mkdocs.org/">MkDocs</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
      
        </div>
      </div>

    </section>

  </div>

  <div class="rst-versions" role="note" aria-label="versions">
  <span class="rst-current-version" data-toggle="rst-current-version">
    
        <span>
          <a href="https://github.com/sequelize/sequelize/" class="fa fa-github" style="color: #fcfcfc"> GitHub</a>
        </span>
    
    
      <span><a href="/v3/docs/models-definition/" style="color: #fcfcfc">« Previous</a></span>
    
    
      <span><a href="/v3/docs/querying/" style="color: #fcfcfc">Next »</a></span>
    
  </span>
</div>
    <script>var base_url = '../..';</script>
    <script src="/v3/js/theme_extra.js" defer=""></script>
    <script src="/v3/js/theme.js" defer=""></script>
      <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js" defer=""></script>
      <script src="/v3/search/main.js" defer=""></script>
    <script defer="">
        window.onload = function () {
            SphinxRtdTheme.Navigation.enable(true);
        };
    </script>



</body></html>